package org.abratuhi.kvngroupware.login.mptua;

import org.abratuhi.kvngroupware.network.AbstractRequestMessageProceeder;
import org.abratuhi.kvngroupware.network.Client;
import org.abratuhi.kvngroupware.network.Message;
import org.abratuhi.kvngroupware.network.MessageSender;
import org.abratuhi.kvngroupware.server.db.ServerDB;
import org.abratuhi.kvngroupware.user.manager.UserManager;
import org.abratuhi.kvngroupware.user.model.User;
import org.jdom.Element;

public class LoginRequestMessageProceeder extends AbstractRequestMessageProceeder{

	MessageSender sender;
	UserManager usermanager;
	ServerDB db;

	public LoginRequestMessageProceeder(MessageSender sender, UserManager usermanager, ServerDB db){
		this.sender = sender;
		this.usermanager = usermanager;
		this.db = db;
	}

	@Override
	public void proceedMessage(Client client, Message message) {
		Element request = message.getRoot().getChild("request");
		String type = request.getAttributeValue("type");
		String action = request.getAttributeValue("action");

		if(type.equals("user")){
			User cuser = User.fromElement((Element) request.getChild("user"));

			String[] attrNames = new String[]{"type", "action", "status"};
			String[] attrValues= new String[]{type, action, "ok"};
			String text = new String();
			Element[] content = new Element[]{cuser.toElement()};
			Message responseMessage;

			boolean okLoginPassword = db.containsLoginPassword(cuser.getId(), cuser.getPassword());
			boolean okLogin = db.containsLogin(cuser.getId());
			User suser = usermanager.get(cuser.getId());
			
			if(action.equals("login")){
				if(okLoginPassword && suser == null){
					content = new Element[]{db.getUser(cuser.getId())};
					usermanager.put(cuser.getId(), cuser);
				}
				else{
					if(suser != null){
						attrValues[2] = "used_id";
					}
					else if(okLogin){
						attrValues[2] = "invalid_password";
					}
					else{
						attrValues[2] = "invalid_id";
					}
				}
			}
			else if(action.equals("logout")){
				if(okLoginPassword){
					usermanager.remove(cuser.getId());
					content = new Element[]{cuser.toElementNoPassword()};
				}
				else if(okLogin){
					attrValues[2] = "invalid_password";
				}
				else{
					attrValues[2] = "invalid_id";
				}
			}

			responseMessage = sender.createMessage(attrNames, attrValues, text, content);
			sender.sendMessage(responseMessage);
		}
	}
}
